﻿// 设置 列表页、明细页的配置信息
(function ()
{
    //去掉  大于小于包括,并改变顺序
    $.ligerDefaults.Filter.operators['string'] =
    $.ligerDefaults.Filter.operators['text'] =
    ["like", "equal", "notequal", "startwith", "endwith"];

    //扩展一个 数字输入 的编辑器
    $.ligerDefaults.Grid.editors['numberbox'] = {
        create: function (container, editParm)
        {
            var column = editParm.column;
            var precision = column.editor.precision;
            var input = $("<input type='text' style='text-align:right' class='l-text' />");
            input.bind('keypress', function (e)
            {
                var keyCode = window.event ? e.keyCode : e.which;
                return keyCode >= 48 && keyCode <= 57 || keyCode == 46 || keyCode == 8;
            });
            input.bind('blur', function ()
            {
                var value = input.val();
                input.val(parseFloat(value).toFixed(precision));
            });
            container.append(input);
            return input;
        },
        getValue: function (input, editParm)
        {
            return parseFloat(input.val());
        },
        setValue: function (input, value, editParm)
        {
            var column = editParm.column;
            var precision = column.editor.precision;
            input.val(value.toFixed(precision));
        },
        resize: function (input, width, height, editParm)
        {
            input.width(width).height(21);
        }
    };
    $.ligerDefaults.Grid.editors['string'] =
    $.ligerDefaults.Grid.editors['text'] = {
        create: function (container, editParm)
        {
            var input = $("<input type='text' style='border:1px solid #d3d3d3;'/>");
            container.append(input);
            return input;
        },
        getValue: function (input, editParm)
        {
            return input.val();
        },
        setValue: function (input, value, editParm)
        {
            input.val(value);
        },
        resize: function (input, width, height, editParm)
        {
            input.width(width).height(21);
        }
    };
    $.ligerDefaults.Grid.editors['select'] =
    {
        create: function (container, editParm)
        {
            var column = editParm.column;
            var input = $("<select></select");
            container.append(input);
            var data = column.editor.data;
            if (!data) return input;
            $(data).each(function ()
            {
                input.append('<option value="' + this.value + '">' + (this.text || this.name) + '</option>');
            });
            return input;
        },
        getValue: function (input, editParm)
        {
            return input.val();
        },
        setValue: function (input, value, editParm)
        {
            if (value)
                input.val(value);
        },
        resize: function (input, width, height, editParm)
        {
            input.css({ width: width, height: 22 });
        }
    };


    var win, winElement, grid, db;

    var gridData = {};

    var currentTableName;

    var fieldTypeData = [{ value: 'text', text: '文本框' }, { value: 'textarea', text: '多行文本框' }, { value: 'date', text: '日期控件' }, { value: 'select', text: '下拉框' }, { value: 'digits', text: '整数输入框' }, { value: 'number', text: '浮点数输入框' }, { value: 'hidden', text: '隐藏控件' }, { value: 'checkbox', text: '复选框'}];

    $.extend($.ligerDefaults.Grid, {
        rowHeight: 24,
        fixedCellHeight: false,
        frozen: false,
        async: true,
        headerRowHeight: 30,
        allowUnSelectRow: true
    });

    /*
    预览界面(grid)
    */

    //搜索框 收缩/展开
    $(".searchtitle .togglebtn").live('click', function ()
    {
        if ($(this).hasClass("togglebtn-down")) $(this).removeClass("togglebtn-down");
        else $(this).addClass("togglebtn-down");
        var searchbox = $(this).parent().nextAll("div.searchbox:first");
        searchbox.slideToggle('fast');
    });


    $("div.switch select").live('change', function ()
    {
        saveGridRows();
        var name = this.value;
        var tableSetting = getTableSetting(name);
        currentTableName = name;
        if (!grid)
        {
            bulidMainGrid(tableSetting);
        }
        else
        {
            grid.set('data', { Rows: bulidGridRows(tableSetting) });
        }
    });

    function getTableSetting(name)
    {
        for (var i = 0; i < db.length; i++)
        {
            if (name == db[i].Name)
                return db[i];
        }
        return null;
    }

    /*
    设置界面(grid)
    */

    window.applySetting = function (dbSetting)
    {
        winElement = $('#setting');

        db = dbSetting;
        if (!db || !db.length) return;

        // db 表 切换 下拉框
        var selectArr = [];
        selectArr.push('<select id="switchSetting">');
        for (var i = 0; i < db.length; i++)
        {
            selectArr.push('<option>' + db[i].Name + '</option>');
        }
        selectArr.push('</select>');
        $("> .switch", winElement).html(selectArr.join());

        //加载第一个表的数据
        currentTableName = db[0].Name;
        if (!grid)
        {
            bulidMainGrid(db[0]);
        }
        else
        {
            grid.set('data', { Rows: bulidGridRows(db[0]) });
        }

        //以窗口的方式显示出来
        if (win)
        {
            win.show();
        }
        else
        {
            win = $.ligerDialog.open({
                width: 800, isResize: true, isDrag: true, title: '设置',
                buttons: [
                    { text: '生成文件', onclick: function (item, dialog)
                    {
                        var d = window.getSettingData();
                        var path = $("#optionPath").val();
                        var category = $("#category").val();
                        LG.ajax({
                            method: 'GenerateUI',
                            data: {
                                data: $.ligerui.toJSON(d),
                                path: path,
                                category: category
                            },
                            success: function (data)
                            {
                                LG.tip('生成代码成功'); 
                            },
                            error: function (message)
                            {
                                LG.tip('生成代码失败：' + message);
                            }
                        });
                    }
                    },
                    { text: '取消', onclick: function (item, dialog) { dialog.hide(); } }
                    ],
                target: winElement
            });
        }
    };

    window.getSettingData = function ()
    {
        saveGridRows();
        var data = [];
        for (var i = 0; i < db.length; i++)
        {
            var t = db[i];
            var rows = gridData[t.Name];
            var tData = bulidData(rows);

            data.push({
                Name: t.Name,
                IdentityColumn: t.IdentityColumn.Name,
                Description: t.Description,
                Grid: $.ligerui.toJSON(tData.grid),
                Form: $.ligerui.toJSON(tData.form),
                Search: $.ligerui.toJSON(tData.search)
            });
        }
        return data;
    };

    function saveGridRows()
    {
        if (!grid) return;
        var rows = [];
        for (var i = 0; i < grid.rows.length; i++)
        {
            rows.push($.extend(true, {}, grid.rows[i]));
        }
        gridData[currentTableName] = rows;
    }

    function bulidGridRows(t)
    {
        if (gridData[t.Name])
        {
            return gridData[t.Name];
        }
        var rows = [];
        $(t.Columns).each(function ()
        {
            var row = {
                name: this.Name,
                display: this.Description,
                listwidth: 180,
                type: 'text',
                width: 220,
                labelwidth: 100,
                space: 30,
                newline: true,
                search_newline: false,
                inlist: true,
                insearch: false,
                inform: true,
                SourceTableName: this.SourceTableName,
                SourceTableIDField: this.SourceTableIDField,
                SourceTableTextField: this.SourceTableTextField
            };
            row.allownull = this.IsNullable ? true : false;
            row.type = this.InputType;
            if (this.IsAutoKey || this.IsInForeignKey || this.IsInPrimaryKey)
            {
                row.inlist = false;
                row.type = "hidden";
            }
            if (this.IsInPrimaryKey)
            {
                row.insearch = false;
                row.type = "hidden";
            }
            if (this.CSharpType == "boo" || this.CSharpType == "bool?")
            {
                row.type = "checkbox";
            }
            if (row.type == "checkbox")
            {
                row.allownull = true;
            }
            if (row.name == "CreateUserID" || row.name == "CreateDate" || row.name == "ModifyUserID" || row.name == "ModifyDate" || row.name == "ModifyDate" || row.name == "RecordStatus")
            {
                row.inlist = row.insearch = row.inform = false;
            }

            if (row.name == "CreateDate")
            {
                row.inlist = true;
            }
            if (row.SourceTableName)
            {
                row.type = "select";
            }
            if (this.isAutoKey)
            {
                row.insearch = false;
            }
            rows.push(row);
        });
        return rows;
    }

    function bulidMainGrid(t)
    {
        var rows = bulidGridRows(t);
        var gridPanle = $('<div style="margin:7px;"></div>').appendTo($("> .list", winElement));
        grid = gridPanle.ligerGrid({
            columns: [
            { display: '基本信息', columns: [
            { display: '字段名', name: 'name', align: 'left', width: 110, minWidth: 30 },
            { display: '显示名', name: 'display', align: 'left', width: 110, minWidth: 30, editor: { type: 'text'} },
            { display: '是否为空', name: 'allownull', width: 55, render: checkboxRender}]
            },
            { display: '列表页设置', columns: [
            { display: '列表显示', name: 'inlist', width: 55, render: checkboxRender },
            { display: '列表宽度', name: 'listwidth', align: 'right', width: 50, minWidth: 30, editor: { type: 'numberbox'} },
            { display: '搜索显示', name: 'insearch', width: 55, render: checkboxRender },
            { display: '是否新行', name: 'search_newline', width: 55, render: checkboxRender}]
            },
            { display: '表单页设置', columns: [
            { display: '表单显示', name: 'inform', width: 55, render: checkboxRender },
            { display: '控件类型', name: 'type', align: 'left', width: 80, minWidth: 30, editor: { type: 'select', data: fieldTypeData }, render: fieldTypeRender },
            { display: '标签宽度', name: 'labelwidth', align: 'right', width: 55, editor: { type: 'numberbox'} },
            { display: '控件宽度', name: 'width', align: 'right', width: 55, editor: { type: 'numberbox'} },
            { display: '间隔宽度', name: 'space', align: 'right', width: 55, editor: { type: 'numberbox'} },
            { display: '是否新行', name: 'newline', width: 55, render: checkboxRender },
                { display: '分组', name: 'group', width: 100, editor: { type: 'text'}}]
            }
       ], data: { Rows: rows }, usePager: false, toolbar: createGridToolbar(),
            enabledEdit: true, clickToEdit: true, fixedCellHeight: false, inWindow: false, rownumbers: true,
            width: '1100', height: '500', heightDiff: -14, rowHeight: 24
        });
    }

    function createGridToolbar(tName)
    {
        var items = [];
        items.push({ text: '预览效果', click: preview, img: "icons/application_view_list.png" });
        items.push({ text: '导出JSON', click: outjson, img: "icons/printer_48.png" });
        items.push({ text: '上移', click: moveup, img: "icons/sign_up.gif" });
        items.push({ text: '下移', click: movedown, img: "icons/arrow_down.gif" });
        //items.push({ text: '自动翻译字段', click: translate, img: "icons/world.gif" });
        return { items: items };

        function clear()
        {
            var managers = $.ligerui.find($.ligerui.controls.Input);
            for (var i = 0, l = managers.length; i < l; i++)
            {
                if (exits(managers[i].id))
                {
                    managers[i].destroy();
                }
            }
        }
        function exits(id)
        {
            for (var i = 0, l = grid.rows.length; i < l; i++)
            {
                var name = grid.rows[i].name;
                if (name == id) return true;
            }
            return false;
        }

        function preview()
        {

            clear();

            var o = bulidData();

            var out = [];
            out.push('<div>');
            out.push('  <div style=" width:98%">');
            out.push('      <div class="searchtitle">');
            out.push('          <span>搜索</span><img src="icons/searchtool.gif" />');
            out.push('          <div class="togglebtn"></div> ');
            out.push('      </div>');
            out.push('      <div class="navline" style="margin-bottom:4px; margin-top:4px;"></div>');
            out.push('      <div class="searchbox">');
            out.push('          <form></form>');
            out.push('      <div class="l-clear"></div>');
            out.push('      </div>');
            out.push('  </div>');
            out.push('  <div class="listgrid"></div> ');
            out.push('</div>');
            var listPanle = $(out.join(''));

            var searchform = $("form:first", listPanle);
            searchform.ligerForm({ fields: o.search });
            var listgrid = $(".listgrid:first", listPanle).ligerGrid({
                columns: o.grid,
                toolbar: listToolbar(), data: null,
                width: '98%', height: 400, checkbox: false
            });
            //搜索 按钮
            LG.appendSearchButtons(searchform, listgrid, false, function ()
            {
                listgrid.options.data = null;
            });

            $.ligerDialog.open({
                title: '预览 列表 界面',
                target: listPanle,
                width: 950, height: 530, isResize: true,
                buttons: [{ text: '关闭', onclick: function (item, dialog) { dialog.hide(); } }]
            });


            function listToolbar()
            {
                var items = [];
                items.push({ text: '增加', click: grid_add, img: "icons/page_add.png" });
                items.push({ text: '修改', click: grid_edit, img: "icons/edit.gif" });
                items.push({ text: '删除', click: grid_delete, img: "icons/delete.png" });
                items.push({ text: '高级自定义查询', click: grid_search, icon: 'search2' });
                return { items: items };

                function grid_add()
                {
                    clear();
                    showDetail(o.form);
                }

                function grid_edit()
                {
                    clear();
                    var selected = listgrid.getSelected();
                    if (!selected) { lab.tip('请选择行'); return; }
                    showDetail(o.form, selected);
                }

                function grid_delete()
                {
                    listgrid.deleteSelectedRow();
                }

                function grid_search()
                {
                    listgrid.options.data = $.extend(true, {}, AllProductData);
                    listgrid.showFilter();
                }
            }
        }
        function showDetail(fields, data)
        {
            var form = $('<form></form> ');
            form.ligerForm({ fields: fields });
            $.ligerDialog.open({
                title: '预览 明细 界面',
                target: form,
                width: 850, height: 400, isResize: true,
                buttons: [{ text: '关闭', onclick: function (item, dialog) { dialog.hide(); } }]
            });
            lab.loadForm(form, data);
        }


        function outjson()
        {
            var d = bulidData();
            var textarea = $("<textarea />").width(400).height(120);
            textarea.val($.ligerui.toJSON(d));
            $.ligerDialog.open({
                title: 'JSON',
                target: textarea.wrap('<div></div>').parent().css('margin', 10),
                width: 470, height: 200, isResize: true,
                buttons: [{ text: '关闭', onclick: function (item, dialog) { dialog.hide(); } }]
            });
        }
        function translate()
        {
            var list = [];
            for (var i = 0, l = grid.rows.length; i < l; i++)
            {
                var o = grid.rows[i];
                list.push(o.name);
            }
            lab.ajax({
                loading: '正在翻译中...',
                url: root + "handle/translate.ashx",
                data: { data: list.join(',') },
                success: function (results)
                {
                    for (var i = 0, l = grid.rows.length; i < l; i++)
                    {
                        grid.rows[i].display = results[i];
                    }
                    grid.reRender({ column: grid.columns[1] });
                }
            });
        }
        function moveup()
        {
            var selected = grid.getSelected();
            if (!selected) return;
            grid.up(selected);
        }
        function movedown()
        {
            var selected = grid.getSelected();
            if (!selected) return;
            grid.down(selected);
        }
    }



    //获取 表单和表格 结构 所需要的数据
    function bulidData(rows)
    {
        var griddata = [], searchdata = [], formdata = [];
        rows = rows || grid.rows;
        for (var i = 0, l = rows.length; i < l; i++)
        {
            var o = rows[i];
            if (o.inlist)
            {
                var gr = { display: o.display, name: o.name, width: o.listwidth };
                if (o.type == "date" || o.type == "checkbocx")
                {
                    gr.type = o.type;
                }
                if (o.type == "text" || o.type == "textean")
                {
                    gr.align = "left";
                }
                else if (o.type == "date")
                {
                    gr.align = "center";
                }
                else
                {
                    gr.align = "right";
                }
                griddata.push(gr);
            }
            if (o.insearch)
                searchdata.push(getFieldData(o, true));
            if (o.inform)
                formdata.push(getFieldData(o));
        }
        return { grid: griddata, search: searchdata, form: formdata };

        function getFieldData(o, search)
        {
            if (o.type == "hidden") return { name: o.name, type: o.type };
            var field = {
                display: o.display,
                name: o.name,
                newline: o.newline,
                labelWidth: o.labelwidth || o.labelWidth,
                width: o.width,
                space: o.space,
                type: o.type
            };
            if (!search)
            {
                field.validate = getValidate(o);
                field.group = o.group;
                field.groupicon = "../lib/icons/communication.gif";
            }
            else
            {
                field.cssClass = "field";
                field.newline = o.search_newline ? true : false;
            }
            if (field.type == "select")
            {
                field.comboboxName = field.name + "Title";
                field.options = {
                    valueFieldID: field.name,
                    url: "../handler/select.ashx?view=" + o.SourceTableName + "&idfield=" + o.SourceTableIDField + "&textfield=" + o.SourceTableTextField
                };
            }
            return field;
        }
        function getValidate(o)
        {
            if (o.validate) return o.validate;
            if (!o.allownull) return { required: true };
            return null;
        }
    }

    //字段类型渲染器
    function fieldTypeRender(r, i, value)
    {
        for (var i = 0, l = fieldTypeData.length; i < l; i++)
        {
            var o = fieldTypeData[i];
            if (o.value == value) return o.text || o.name;
        }
        return "文本框";
    }

})();